﻿#include "Application.h"

#include <iostream>

Application::Application(const AppArgs &args)
    : m_args(args)
{
  InitApp();
}

Application::~Application() {
}

void Application::Run()
{
  MainLoop();
  Shutdown();
}

void Application::InitApp()
{
  LOG_TRACE("App Starting");
  
  m_window = CreateRef<Window>(m_args.windowWidth, m_args.windowHeight, m_args.windowTitle.c_str());
  m_gui = CreateRef<Gui>(m_window);
}

void Application::MainLoop()
{
  OnInit();

  LOG_TRACE("App Running");
  // 主循环
  while (!m_window->ShouldClose())
  {
    m_window->PollEvents();

    // 计算帧时间
    static float lastFrame = 0.0f;
    float currentFrame = static_cast<float>(glfwGetTime());
    m_deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;

    OnUpdate(m_deltaTime);

    if (m_window->ShouldRender())
    {
      m_window->BeginFrame();
      OnRender();
      m_window->FinalizeFrame();
      
      m_gui->BeginFrame();
      OnRenderGui();
      m_gui->FinalizeFrame();
      
      m_window->SwapBuffers();
    }
  }

  OnShutdown();
}

void Application::Shutdown()
{
  LOG_TRACE("App Shutdown");
}